package com.ruoyi.statisticalCenter.service.impl;

import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.statisticalCenter.domain.ScOutboundEliminate;
import com.ruoyi.statisticalCenter.mapper.ScOutboundEliminateMapper;
import com.ruoyi.statisticalCenter.service.ScOutboundEliminateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ScOutboundEliminateServiceImpl implements ScOutboundEliminateService {
    @Autowired
    private ScOutboundEliminateMapper scOutboundEliminateMapper;

    @Override
    public R importStudent(List<ScOutboundEliminate> list) {
        if (CollectionUtils.isEmpty(list)) {
            return R.fail("导入数据不能为空！");
        }

        List<ScOutboundEliminate> successfulImports = new ArrayList<>();
        for (ScOutboundEliminate scOutboundEliminate : list) {
            String transportCode = scOutboundEliminate.getTransportCode();

            // 防止空指针异常，检查运单号是否为null
            if (transportCode == null) {
                log.error("发现运单号为空的记录，跳过导入：{}", scOutboundEliminate);
                continue; // 跳过当前循环，处理下一条记录
            }

            Integer isExist = scOutboundEliminateMapper.selectByTransportCode(transportCode);
            if (isExist != 1) {
                scOutboundEliminate.setSettleTime(scOutboundEliminate.getSettleTime().replace("-", ""));
                scOutboundEliminateMapper.insert(scOutboundEliminate);
            } else {
                log.warn("跳过了已存在运单号的记录：{}", scOutboundEliminate);
            }
        }

        int importedCount = successfulImports.size();
        String message = importedCount == list.size()
                ? "导入成功"
                : String.format("部分导入成功，共导入 %d 条记录，跳过了 %d 条已存在运单号的记录", importedCount, list.size() - importedCount);

        return R.ok(message);
    }
    @Override
    public List<ScOutboundEliminate> select() {
        return scOutboundEliminateMapper.select();
    }
}
